<script setup>
import { ref, watchEffect, computed } from 'vue'
import {
  Icon,
  Popover,
  RadioGroup,
  Radio,
  Form,
  Field,
  CellGroup,
  Picker,
  Popup,
  showToast,
  showLoadingToast,
  Search,
} from 'vant'
import Utility from '@/utils/utility'
import UploadFile from '@/components/uploadFile/index.vue'
// import BigMath from '@yw/cloud.utilities.big-math'
import commonModel from '@/http/modules/common.js'
import {
  contractNoValidator,
  buyerNameValidator,
  amountValidator,
  trimObject,
} from '@/utils/validator.js'
import cgToast from '@/components/toast/index.js'
import { enumStore } from '@/store/enum'
import { storeToRefs } from 'pinia'
const enum_store = enumStore()
const { enumDslInfo } = storeToRefs(enum_store)
const emits = defineEmits(['checkSuccess','sketchContactId'])
defineExpose({ checkForm, sketchForm })
const props = defineProps({
  contractDetail: {
    type: Object,
    default: () => {},
  },
  editContractId: {
    // 编辑id
    type: [String, Number],
    default: '',
  },
  contractId: {
    //  回退合同Id
    type: [String, Number],
    default: '',
  },
})

let showRegionPicker = ref(false)
let showCurrencyPicker = ref(false)
const RefHTFile = ref()
const RefCIFile = ref()
const RefForm = ref()
const regionList = ref([])
const isSketch = ref(false)
const regionSearchKey = ref('')
const form = ref({
  regionName: '',
  currencyStr: '',
  declType: 'Y', // 申报模式
  contractNo: '', // 合同编号
  region: '', // 贸易国家或地区
  buyerName: '', // 买家英文名称
  totalOrderAmount: null, // 订单总金额
  currency: '', // 币种
  payType: '00', // 付款方式
  prepayAmount: null, // 预付款金额
  balanceAmount: null, // 尾款金额
  ciPiUrlsName: '',
  ciPiUrls: '',
  contractUrlsName: '',
  contractUrls: '',
})
const contractUrls = ref('')
const ciPiUrls = ref('')
const contractUrlsName = ref('')
const ciPiUrlsName = ref('')
const coinCombineList = computed(() => {
  if (enumDslInfo.value.CurrencyType && enumDslInfo.value.CurrencyType.length) {
    return enumDslInfo.value.CurrencyType.filter(v=>v.value !== 'CNY').map((_) => ({
      ..._,
      combineName: _.value + '-' + _.name,
    }))
  } else {
    return []
  }
})
// const isSketched = ref(false)
watchEffect(() => {
  regionList.value = enumDslInfo.value.Nationality
})
function onRegionConfirm({ selectedOptions }) {
  showRegionPicker.value = false
  const { label, value } = selectedOptions[0]
  form.value.regionName = label
  form.value.region = value
}
function onCurrencyConfirm({ selectedOptions }) {
  showCurrencyPicker.value = false
  const { combineName, value } = selectedOptions[0]
  form.value.currencyStr = combineName
  form.value.currency = value
}
function checkForm() {
  isSketch.value = false
  RefForm.value.submit()
}
function sketchForm() {
  isSketch.value = true
  onSubmit()
}
async function onSubmit() {
  let loading = null
  try {
    const htFileList = RefHTFile.value.fileList || []
    // const htFileNameList = RefHTFile.value.fileNameList || []
    const ciFileList = RefCIFile.value.fileList || []
    // const ciFileNameList = RefCIFile.value.fileNameList || []
    if (!form.value.contractNo) {
      showToast('请填写合同编号')
      return false
    }
    const { payType, prepayAmount, balanceAmount, totalOrderAmount } =
      form.value
    if (!isSketch.value) {
      if (
        payType === '01' &&
        !Utility.highPrecisionEqual(
          totalOrderAmount,
          prepayAmount,
          balanceAmount
        )
      ) {
        showToast('预付款金额+尾款金额必须等于总金额')
        return false
      }
      if (!htFileList.length && !ciFileList.length) {
        showToast('请上传CI、PI或合同,最少一项')
        return false
      }
    }
    if (payType !== '01') {
      form.value.prepayAmount = null
      form.value.balanceAmount = null
    }
    form.value.ciPiUrls = ciFileList.join(',')
    form.value.contractUrls = htFileList.join(',')
    // form.value.ciPiUrlsName = ciFileNameList.map((it) => it.name).join(',')
    // form.value.contractUrlsName = htFileNameList.map((it) => it.name).join(',')
    form.value.setExc = 'Y'
    loading = showLoadingToast({
      message: '请求中...',
      duration: 0,
      forbidClick: true,
    })
    let params = {}
    if (props.editContractId) {
      params = {
        contractOrderNo: props.editContractId,
        ...trimObject(form.value),
      }
    } else if (props.contractId) {
      params = { contractOrderNo: props.contractId, ...trimObject(form.value) }
    } else {
      params = trimObject(form.value)
    }
    // const params = props.editContractId
    //   ? { contractOrderNo: props.editContractId, ...trimObject(form.value) }
    //   : trimObject(form.value)
    // 进来没数据并且没有做过暂存操作
    if ([undefined, 'Draft'].includes(props.contractDetail.contractStatus)) {
    commonModel
      .gatewayApi({
        bizContent: {
          ...params,
          source: sessionStorage.source || '',
        },
        service: 'cb_trade_temp_store_contract',
        version: '1.0.0',
      })
      .then((result) => {
        if (result) {
          // isSketched.value = true
          if (isSketch.value) {
            //暂存
            cgToast.open({
              title: '暂存成功',
              cancelText: '返回',
              confirmText: '下一步',
              confirmFun: () => {
                emits('sketchContactId',result.contractOrderNo )
                cgToast.close()
                checkForm()
              },
              cancelFun: () => {
                emits('sketchContactId',result.contractOrderNo )
                cgToast.close()
              },
            })
          } else {
            emits(
              'checkSuccess',
              result.contractOrderNo,
              form.value.declType === 'Y'
            )
          }
        }
      })
      .catch((error) => {
        if (isSketch.value) {
          // 暂存失败处理
          cgToast.open({
            title: '暂存失败',
            content: error.subMsg || error.msg,
            type: 'warning',
            showCancel: false,
            confirmFun: () => {
              cgToast.close()
            },
          })
        }
      })
    } else {
      emits('checkSuccess', '', form.value.declType === 'Y', params)
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading && loading.close()
  }
}
watchEffect(() => {
  if (props.editContractId) {
    if (props.contractDetail && JSON.stringify(props.contractDetail) !== '{}') {
      form.value = Object.assign({}, props.contractDetail.contractInfo)
      form.value.currencyStr = Utility.getTargetByValue(
        coinCombineList.value,
        props.contractDetail.contractInfo.currency
      ).combineName
      form.value.regionName = Utility.getTargetByValue(
        enumDslInfo.value.Nationality,
        props.contractDetail.contractInfo.region
      ).name
      ciPiUrls.value = props.contractDetail.contractInfo.ciPiUrls
      contractUrls.value = props.contractDetail.contractInfo.contractUrls
    }
  }
})
async function handleRegionSearch(key) {
  key = key.trim()
  if (key) {
    regionList.value = enumDslInfo.value.Nationality.filter(
      (it) => it.label.indexOf(key) !== -1
    )
  } else {
    regionList.value = enumDslInfo.value.Nationality
  }
}
</script>

<template>
  <div class="contract__order">
    <div class="order__item">
      <div class="item__label">申请结汇</div>
      <div class="item__value">
        <Popover class="tips__popover">
          <div class="tips__box-popover">
            <p>根据监管要求，人民币结汇时，将贸易合同订单材料作为结汇依据；</p>
            <p>
              *申报结汇:
              由境内合作银行和持牌支付机构提供境内合规入账服务，代您提交申报结汇材料.
            </p>
          </div>
          <template #reference>
            是<Icon name="warning" color="#ccc"></Icon>
          </template>
        </Popover>
      </div>
    </div>
    <div class="order__item">
      <div class="item__label">申报模式</div>
      <div class="item__value">
        <RadioGroup v-model="form.declType" direction="horizontal">
          <Radio name="Y">报关单</Radio>
          <Radio name="N">非报关单</Radio>
        </RadioGroup>
      </div>
    </div>
    <div class="order__form">
      <div class="order__form-title">合同订单信息</div>
      <Form @submit="onSubmit" label-width="7em" ref="RefForm">
        <CellGroup>
          <Field
            v-model="form.contractNo"
            name="contractNo"
            label="合同编号"
            placeholder="请输入合同编号"
            :rules="[
              { required: true, message: '请输入合同编号' },
              {
                validator: contractNoValidator,
                message: '不可超过64个字符，中间不可有空格',
              },
            ]"
          />
          <Field
            v-model="form.regionName"
            name="region"
            label="贸易国家和地区"
            placeholder="请选择"
            readonly
            is-link
            :rules="[{ required: true, message: '请选择贸易国家和地区' }]"
            @click="showRegionPicker = true"
          />
          <Popup v-model:show="showRegionPicker" position="bottom">
            <Search
              v-model="regionSearchKey"
              @search="handleRegionSearch"
              placeholder="请输入搜索关键词"
            />
            <Picker
              :columns="regionList"
              :columns-field-names="{ text: 'label', value: 'value' }"
              @confirm="onRegionConfirm"
              @cancel="showRegionPicker = false"
            />
          </Popup>
          <Field
            v-model="form.buyerName"
            name="buyerName"
            label="买家英文名称"
            placeholder="请输入买家英文名称"
            :rules="[
              { required: true, message: '请输入买家英文名称' },
              {
                validator: buyerNameValidator,
                message: '不支持汉字，不能超过64个字符',
              },
            ]"
          />
          <Field
            v-model="form.totalOrderAmount"
            name="totalOrderAmount"
            label="总金额"
            placeholder="请输入总金额"
            :rules="[
              { required: true, message: '请输入总金额' },
              {
                validator: amountValidator,
                message: '只支持数字及小数点后两位，不可超过15个字符',
              },
            ]"
          />
          <Field
            v-model="form.currencyStr"
            name="currency"
            label="币种"
            placeholder="请选择"
            readonly
            is-link
            :rules="[{ required: true, message: '请选择币种' }]"
            @click="showCurrencyPicker = true"
          />
          <Popup v-model:show="showCurrencyPicker" position="bottom">
            <Picker
              :columns="coinCombineList"
              :columns-field-names="{ text: 'combineName', value: 'value' }"
              @confirm="onCurrencyConfirm"
              @cancel="showCurrencyPicker = false"
            />
          </Popup>
          <Field
            v-model="form.payType"
            name="payType"
            label="付款方式"
            placeholder="请输入"
          >
            <template v-slot:input>
              <RadioGroup
                v-model="form.payType"
                direction="horizontal"
                class="pay__type-group"
              >
                <Radio name="01">预付+尾款</Radio>
                <Radio name="00">全额预付</Radio>
              </RadioGroup>
            </template>
          </Field>
          <template v-if="form.payType === '01'">
            <Field
              v-model="form.prepayAmount"
              name="prepayAmount"
              label="预付款金额"
              placeholder="请输入预付款金额"
              :rules="[
                { required: true, message: '请输入预付款金额' },
                {
                  validator: amountValidator,
                  message: '只支持数字及小数点后两位，不可超过15个字符',
                },
              ]"
            >
            </Field>
            <Field
              v-model="form.balanceAmount"
              name="balanceAmount"
              label="尾款金额"
              placeholder="请输入尾款金额"
              :rules="[
                { required: true, message: '请输入尾款金额' },
                {
                  validator: amountValidator,
                  message: '只支持数字及小数点后两位，不可超过15个字符',
                },
              ]"
            >
            </Field>
          </template>
        </CellGroup>
      </Form>
    </div>
    <div class="file__box">
      <div class="file__box-title">
        请上传CI、PI或合同,最少一项,更多额外发票附件， 有利于加快审核速度
      </div>
      <upload-file
        title="合同"
        ref="RefHTFile"
        :is-upload-file="contractUrls"
        :is-upload-file-name="contractUrlsName"
      />
      <div class="line" />
      <upload-file
        title="CI/PI"
        ref="RefCIFile"
        :is-upload-file="ciPiUrls"
        :is-upload-file-name="ciPiUrlsName"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.contract__order {
  padding: 10px 12px;
  .order__item {
    width: 100%;
    padding: 17px 12px;
    background: #ffffff;
    border-radius: 8px;
    display: flex;
    font-size: 16px;
    font-weight: 500;
    color: #222222;
    margin-bottom: 10px;
    .item__label {
      width: 100px;
      margin-right: 20px;
    }
    .item__value {
      display: flex;
      align-items: center;
      i.van-icon-warning {
        margin-left: 2px;
      }
    }
  }
  .order__form {
    width: 100%;
    background: #ffffff;
    border-radius: 8px;
    padding: 8px 12px 0 12px;
    .order__form-title {
      font-size: 16px;
      font-weight: 500;
      color: #222222;
      margin-bottom: 8px;
      line-height: 20px;
    }
  }
  .file__box {
    margin-top: 10px;
    background: #ffffff;
    border-radius: 8px;
    padding: 12px 12px 0;
    .file__box-title {
      font-size: 14px;
      font-weight: 500;
      color: #222222;
      line-height: 20px;
    }
    .line {
      width: 100%;
      height: 1px;
      background: #eeeeee;
    }
  }
}
:deep {
  .pay__type-group {
    .van-radio:last-of-type {
      margin-right: 0;
    }
  }
}
</style>
<style>
.van-popover--light.tips__popover {
  width: 50%;
}
.tips__box-popover {
  font-size: 14px;
  color: #222222;
  padding: 10px;
}
</style>
